﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using SiteServer.Plugin;
using Thingpower.SS.EduOnline.Model;

namespace Thingpower.SS.EduOnline.Provider
{
    public class UserDAO : BaseDAO
    {
        public const string TableName = "siteserver_User";

        private const string ParmUserName = "@UserName";
        private const string ParmLastActivityDate = "@LastActivityDate";
        private const string ParmCountOfLogin = "@CountOfLogin";
        private const string ParmCountOfFailedLogin = "@CountOfFailedLogin";

        public static int GetCount(string queryExpression)
        {
            string sqlString = $@"SELECT COUNT(*) FROM {TableName} WHERE {queryExpression}";

            return int.Parse(DataApi.ExecuteScalar(ConnectionString, sqlString).ToString());

        }

        public static void UpdateLastActivityDateAndCountOfFailedLogin(string userName)
        {
            if (string.IsNullOrEmpty(userName)) return;

            var sqlString = $"UPDATE {TableName} SET LastActivityDate = @LastActivityDate, {DataApi.ToPlusSqlString("CountOfFailedLogin", 1)} WHERE UserName = @UserName";

            IDataParameter[] updateParms = {
                DataApi.GetParameter(ParmLastActivityDate, DateTime.Now),
                DataApi.GetParameter(ParmUserName, userName)
            };

            DataApi.ExecuteNonQuery(ConnectionString, sqlString, updateParms);

        }

        public static void UpdateLastActivityDateAndResetCountOfFailedLogin(string userName)
        {
            if (string.IsNullOrEmpty(userName)) return;

            var sqlString = $"UPDATE {TableName} SET LastActivityDate = @LastActivityDate, CountOfFailedLogin = 0 WHERE UserName = @UserName";

            IDataParameter[] updateParms = {
                DataApi.GetParameter(ParmLastActivityDate, DateTime.Now),
                DataApi.GetParameter(ParmUserName, userName)
            };

            DataApi.ExecuteNonQuery(ConnectionString, sqlString, updateParms);

        }

        public static void UpdateLastActivityDateAndCountOfLogin(string userName)
        {
            if (string.IsNullOrEmpty(userName)) return;

            var sqlString = $"UPDATE {TableName} SET LastActivityDate = @LastActivityDate, {DataApi.ToPlusSqlString("CountOfLogin", 1)}, CountOfFailedLogin = 0 WHERE UserName = @UserName";

            IDataParameter[] updateParms = {
                DataApi.GetParameter(ParmLastActivityDate, DateTime.Now),
                DataApi.GetParameter(ParmUserName, userName)
            };

            DataApi.ExecuteNonQuery(ConnectionString, sqlString, updateParms);
        }

    }
}